package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper articleMapper;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //查询5天内的所有文章
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> articleListByDays = articleMapper.findArticleListByDays(date);
        //计算文章的分值
        List<HotArticleVo> hotArticleVos = computeHotArticle(articleListByDays);
        //把每个频道的文章保存到redis
        cacheTagToRedis(hotArticleVos);
    }

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 保存热点文章到redis
     *
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        //查询出所有的频道
        ResponseResult responseResult = wemediaClient.getChannels();
        if (responseResult.getCode().equals(200)) {
            String jsonStr = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(jsonStr, WmChannel.class);
            //把所有文章按照频道归类
            for (WmChannel wmChannel : wmChannels) {
                List<HotArticleVo> articleVoList = hotArticleVos.stream()
                        .filter(hotArticleVo -> hotArticleVo.getChannelId() != null && hotArticleVo.getChannelId().equals(wmChannel.getId()))
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
                //保存归类文章到redis
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(),
                        JSON.toJSONString(articleVoList));
            }

           //保存推荐数据到首页
            List<HotArticleVo> voList = hotArticleVos.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .limit(30)
                    .collect(Collectors.toList());
            cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE  + ArticleConstants.DEFAULT_TAG,
                    JSON.toJSONString(voList));
        }

    }


    /**
     * 计算文章分值
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> articleList) {
        ArrayList<HotArticleVo> voList = new ArrayList<>(articleList.size());
        for (ApArticle article : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            //属性拷贝
            BeanUtils.copyProperties(article, hotArticleVo);
            //计算文章分值
            Integer score = computeScore(article);
            hotArticleVo.setScore(score);
            voList.add(hotArticleVo);

        }
        return voList;
    }

    /**
     * 计算文章具体分值
     *
     * @param article
     * @return
     */
    private Integer computeScore(ApArticle article) {
        Integer score = 0;
        if (article.getLikes() != null) {
            score = +article.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (article.getCollection() != null) {
            score += article.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        if (article.getComment() != null) {
            score += article.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (article.getViews() != null) {
            score += article.getViews();
        }
        return score;
    }
}























